<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    @cancel="handleCancel"
    :footer="null"
    :maskClosable="false">
    
    <a-spin :spinning="confirmLoading">
      <a-tabs defaultActiveKey="1">
        <!-- 基本信息 Tab -->
        <a-tab-pane key="1" tab="基本信息">
          <a-descriptions :column="2" bordered>
            <a-descriptions-item label="供应商编码">{{ model.supplierCode }}</a-descriptions-item>
            <a-descriptions-item label="供应商名称">{{ model.supplierName }}</a-descriptions-item>
            <a-descriptions-item label="供应商类型">
              <j-dict-tag :value="model.supplierType || ''" dictCode="supplier_type"/>
            </a-descriptions-item>
            <a-descriptions-item label="主要联系人">{{ model.contactPerson }}</a-descriptions-item>
            <a-descriptions-item label="联系电话">{{ model.contactPhone }}</a-descriptions-item>
            <a-descriptions-item label="电子邮箱">{{ model.email }}</a-descriptions-item>
            <a-descriptions-item label="信用等级">
              <j-dict-tag :value="model.creditLevel || ''" dictCode="supplier_credit_level"/>
            </a-descriptions-item>
            <a-descriptions-item label="合作状态">
              <j-dict-tag :value="model.cooperationStatus || ''" dictCode="supplier_cooperation_status"/>
            </a-descriptions-item>
            <a-descriptions-item label="税号">{{ model.taxNumber }}</a-descriptions-item>
            <a-descriptions-item label="开户银行">{{ model.bankName }}</a-descriptions-item>
            <a-descriptions-item label="银行账号" :span="2">{{ model.bankAccount }}</a-descriptions-item>
            <a-descriptions-item label="地址" :span="2">{{ model.address }}</a-descriptions-item>
            <a-descriptions-item label="备注" :span="2">{{ model.remark }}</a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>
        
        <!-- 联系人 Tab -->
        <a-tab-pane key="2" tab="联系人">
          <div class="table-page-search-wrapper">
            <a-button type="primary" icon="plus" @click="handleAddContact" style="margin-bottom: 10px">新增联系人</a-button>
            
            <a-table
              size="middle"
              bordered
              rowKey="id"
              :columns="contactColumns"
              :dataSource="contactList"
              :pagination="false"
              :loading="contactLoading">
              
              <template slot="isPrimarySlot" slot-scope="text, record">
                <a-switch 
                  :checked="text === 1" 
                  @change="(checked) => handleTogglePrimaryContact(checked, record)"
                  :disabled="text === 1"
                />
              </template>
              
              <span slot="action" slot-scope="text, record">
                <a @click="handleEditContact(record)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm 
                  title="确定删除吗?" 
                  @confirm="() => handleDeleteContact(record.id)"
                  :disabled="record.isPrimary === 1"
                >
                  <a :style="{ color: record.isPrimary === 1 ? '#aaa' : '' }">
                    {{ record.isPrimary === 1 ? '主要联系人不可删除' : '删除' }}
                  </a>
                </a-popconfirm>
              </span>
            </a-table>
          </div>
        </a-tab-pane>
        
        <!-- 物料关联 Tab -->
        <a-tab-pane key="3" tab="物料关联">
          <div class="table-page-search-wrapper">
            <a-button type="primary" icon="plus" @click="handleAddMaterial" style="margin-bottom: 10px">新增物料关联</a-button>
            
            <a-table
              size="middle"
              bordered
              rowKey="id"
              :columns="materialColumns"
              :dataSource="materialList"
              :pagination="false"
              :loading="materialLoading">
              
              <span slot="isPreferredSlot" slot-scope="text">
                <j-dict-tag :value="text || ''" dictCode="yn"/>
              </span>
              
              <span slot="materialImagesSlot" slot-scope="text">
                <div v-if="text" class="material-images-container">
                  <a-carousel dots-position="bottom" arrows autoplay>
                    <div v-for="(img, index) in getImagesArray(text)" :key="index" class="material-image-item">
                      <img :src="getImageUrl(img)" @click="handlePreviewImage(img)" alt="物料图片" 
                           @error="handleImageError" class="material-image"/>
                    </div>
                  </a-carousel>
                </div>
                <span v-else>-</span>
              </span>
              
              <span slot="action" slot-scope="text, record">
                <a @click="handleEditMaterial(record)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteMaterial(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </span>
            </a-table>
          </div>
        </a-tab-pane>
        
        <!-- 采购历史 Tab -->
        <a-tab-pane key="4" tab="采购历史">
          <a-table
            size="middle"
            bordered
            rowKey="id"
            :columns="purchaseColumns"
            :dataSource="purchaseList"
            :pagination="false"
            :loading="purchaseLoading">
            
            <span slot="statusSlot" slot-scope="text">
              <j-dict-tag :value="text || ''" dictCode="purchase_order_status"/>
            </span>
          </a-table>
        </a-tab-pane>
      </a-tabs>
      
      <!-- 联系人表单 Modal -->
      <a-modal
        :title="contactTitle"
        :width="800"
        :visible="contactVisible"
        :confirmLoading="contactConfirmLoading"
        @ok="handleContactSubmit"
        @cancel="handleContactCancel">
        <a-form :form="contactForm">
          <a-form-item label="联系人姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input placeholder="请输入联系人姓名" v-decorator="['name', {rules: [{required: true, message: '请输入联系人姓名!'}]}]" />
          </a-form-item>
          <a-form-item label="职位" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input placeholder="请输入职位" v-decorator="['position']" />
          </a-form-item>
          <a-form-item label="电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input placeholder="请输入电话" v-decorator="['phone', {rules: [{required: true, message: '请输入电话!'}]}]" />
          </a-form-item>
          <a-form-item label="电子邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input placeholder="请输入电子邮箱" v-decorator="['email']" />
          </a-form-item>
          <a-form-item label="是否主要联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="!contactModel.id">
            <j-dict-select-tag type="list" v-decorator="['isPrimary', {initialValue: '0'}]" :trigger-change="true" dictCode="yn" placeholder="请选择是否主要联系人" />
          </a-form-item>
          <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-textarea placeholder="请输入备注" v-decorator="['remark']" :rows="4" />
          </a-form-item>
        </a-form>
      </a-modal>
      
      <!-- 物料关联表单 Modal -->
      <a-modal
        :title="materialTitle"
        :width="800"
        :visible="materialVisible"
        :confirmLoading="materialConfirmLoading"
        @ok="handleMaterialSubmit"
        @cancel="handleMaterialCancel">
        <a-form :form="materialForm">
          <a-form-item label="物料编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input placeholder="请输入物料编码" v-decorator="['materialCode', {rules: [{required: true, message: '请输入物料编码!'}]}]" />
          </a-form-item>
          <a-form-item label="物料图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-image-upload 
              v-decorator="['materialImages']" 
              :number="5"
              :isMultiple="true"
              bizPath="supplier/material"
              :returnUrl="true"
              @change="handleMaterialImagesChange"
            ></j-image-upload>
          </a-form-item>
          <a-form-item label="价格" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number style="width: 100%" placeholder="请输入价格" v-decorator="['price', {initialValue: 0}]" :min="0" :step="0.01" />
          </a-form-item>
          <a-form-item label="交货周期(天)" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number style="width: 100%" placeholder="请输入交货周期" v-decorator="['leadTime', {initialValue: 0}]" :min="0" :step="1" />
          </a-form-item>
          <a-form-item label="最小订购量" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number style="width: 100%" placeholder="请输入最小订购量" v-decorator="['minOrderQuantity', {initialValue: 0}]" :min="0" :step="0.01" />
          </a-form-item>
          <a-form-item label="物料单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input placeholder="请输入物料单位" v-decorator="['unit']" />
          </a-form-item>
          <a-form-item label="是否首选" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-dict-select-tag type="list" v-decorator="['isPreferred', {initialValue: '0'}]" :trigger-change="true" dictCode="yn" placeholder="请选择是否首选" />
          </a-form-item>
          <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-textarea placeholder="请输入备注" v-decorator="['remark']" :rows="4" />
          </a-form-item>
        </a-form>
      </a-modal>
      
      <div style="text-align: center; margin-top: 16px">
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" @click="handleEdit" style="margin-left: 8px">编辑</a-button>
      </div>
    </a-spin>
    
    <!-- 图片预览模态框 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="物料图片" style="width: 100%" :src="previewImage" />
    </a-modal>
  </a-modal>
</template>

<script>
  import { supplierDetail, supplierEdit } from '@/api/wms/supplier'
  import { contactListBySupplier, contactAdd, contactEdit, contactDelete } from '@/api/wms/supplier'
  import { materialListBySupplier, materialAdd, materialEdit, materialDelete } from '@/api/wms/supplier'
  import { supplierPurchaseHistory } from '@/api/wms/supplier'
  import JDictTag from '@/components/dict/JDictTag.vue'
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import JImageUpload from '@/components/jeecg/JImageUpload'
  import { getFileAccessHttpUrl } from '@/api/manage'
  import pick from 'lodash.pick'
  
  export default {
    name: "SupplierDetailModal",
    components: {
      JDictTag,
      JDictSelectTag,
      JImageUpload
    },
    data () {
      return {
        title: "供应商详情",
        visible: false,
        model: {},
        confirmLoading: false,
        labelCol: {
          span: 6
        },
        wrapperCol: {
          span: 18
        },
        
        // 联系人相关
        contactList: [],
        contactLoading: false,
        contactVisible: false,
        contactConfirmLoading: false,
        contactTitle: "新增联系人",
        contactForm: this.$form.createForm(this),
        contactModel: {},
        contactColumns: [
          {
            title: '联系人姓名',
            align: "center",
            dataIndex: 'name'
          },
          {
            title: '职位',
            align: "center",
            dataIndex: 'position'
          },
          {
            title: '电话',
            align: "center",
            dataIndex: 'phone'
          },
          {
            title: '电子邮箱',
            align: "center",
            dataIndex: 'email'
          },
          {
            title: '主要联系人',
            align: "center",
            dataIndex: 'isPrimary',
            scopedSlots: { customRender: 'isPrimarySlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: { customRender: 'action' }
          }
        ],
        
        // 物料关联相关
        materialList: [],
        materialLoading: false,
        materialVisible: false,
        materialConfirmLoading: false,
        materialTitle: "新增物料关联",
        materialForm: this.$form.createForm(this),
        materialModel: {},
        materialColumns: [
          {
            title: '物料编码',
            align: "center",
            dataIndex: 'materialCode'
          },
          {
            title: '物料图片',
            align: "center",
            dataIndex: 'materialImages',
            scopedSlots: { customRender: 'materialImagesSlot' }
          },
          {
            title: '价格',
            align: "center",
            dataIndex: 'price'
          },
          {
            title: '交货周期(天)',
            align: "center",
            dataIndex: 'leadTime'
          },
          {
            title: '最小订购量',
            align: "center",
            dataIndex: 'minOrderQuantity'
          },
          {
            title: '物料单位',
            align: "center",
            dataIndex: 'unit'
          },
          {
            title: '是否首选',
            align: "center",
            dataIndex: 'isPreferred',
            scopedSlots: { customRender: 'isPreferredSlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: { customRender: 'action' }
          }
        ],
        
        // 采购历史相关
        purchaseList: [],
        purchaseLoading: false,
        purchaseColumns: [
          {
            title: '采购单号',
            align: "center",
            dataIndex: 'purchaseNo'
          },
          {
            title: '采购日期',
            align: "center",
            dataIndex: 'purchaseDate'
          },
          {
            title: '总金额',
            align: "center",
            dataIndex: 'totalAmount'
          },
          {
            title: '状态',
            align: "center",
            dataIndex: 'status',
            scopedSlots: { customRender: 'statusSlot' }
          }
        ],
        
        // 图片预览相关
        previewVisible: false,
        previewImage: '',
        materialImages: [] // 物料图片列表
      }
    },
    methods: {
      show(record) {
        this.visible = true;
        this.model = Object.assign({}, record);
        this.loadData(this.model.id);
      },
      loadData(id) {
        this.confirmLoading = true;
        supplierDetail(id).then(res => {
          if (res.success) {
            this.model = res.result;
            this.loadContactList(id);
            this.loadMaterialList(id);
            this.loadPurchaseHistory(id);
          } else {
            this.$message.warning(res.message);
          }
          this.confirmLoading = false;
        });
      },
      loadContactList(supplierId) {
        this.contactLoading = true;
        contactListBySupplier(supplierId).then(res => {
          if (res.success) {
            this.contactList = res.result;
          } else {
            this.$message.warning(res.message);
          }
          this.contactLoading = false;
        });
      },
      loadMaterialList(supplierId) {
        this.materialLoading = true;
        materialListBySupplier(supplierId).then(res => {
          if (res.success) {
            this.materialList = res.result;
          } else {
            this.$message.warning(res.message);
          }
          this.materialLoading = false;
        });
      },
      loadPurchaseHistory(supplierId) {
        this.purchaseLoading = true;
        supplierPurchaseHistory({supplierId: supplierId}).then(res => {
          if (res.success) {
            this.purchaseList = res.result.records || [];
          } else {
            this.$message.warning(res.message);
          }
          this.purchaseLoading = false;
        });
      },
      handleCancel() {
        this.visible = false;
      },
      handleEdit() {
        this.$emit('edit', this.model);
        this.visible = false;
      },
      
      // 切换主要联系人
      handleTogglePrimaryContact(checked, record) {
        if (checked) {
          this.contactConfirmLoading = true;
          
          // 1. 先将所有联系人设为非主要联系人
          const promises = this.contactList
            .filter(contact => contact.isPrimary === 1 && contact.id !== record.id)
            .map(contact => {
              const updatedContact = { ...contact, isPrimary: 0 };
              return contactEdit(updatedContact);
            });
          
          // 2. 将当前联系人设为主要联系人
          const updatedRecord = { ...record, isPrimary: 1 };
          promises.push(contactEdit(updatedRecord));
          
          // 3. 更新供应商的主要联系人信息
          const updatedSupplier = {
            id: this.model.id,
            contactPerson: record.name,
            contactPhone: record.phone,
            email: record.email
          };
          
          promises.push(supplierEdit(updatedSupplier));
          
          // 等待所有请求完成
          Promise.all(promises)
            .then(() => {
              this.$message.success('已成功设置主要联系人');
              // 重新加载数据
              this.loadData(this.model.id);
            })
            .catch(error => {
              this.$message.error('设置主要联系人失败: ' + error.message);
            })
            .finally(() => {
              this.contactConfirmLoading = false;
            });
        }
      },
      
      // 联系人相关方法
      handleAddContact() {
        this.contactForm.resetFields();
        this.contactModel = {};
        this.contactTitle = "新增联系人";
        this.contactVisible = true;
      },
      handleEditContact(record) {
        this.contactForm.resetFields();
        this.contactModel = Object.assign({}, record);
        this.contactTitle = "编辑联系人";
        this.contactVisible = true;
        this.$nextTick(() => {
          this.contactForm.setFieldsValue(pick(this.contactModel, 'name', 'position', 'phone', 'email', 'isPrimary', 'remark'));
        });
      },
      handleDeleteContact(id) {
        // 检查是否为主要联系人
        const contact = this.contactList.find(item => item.id === id);
        if (contact && contact.isPrimary === 1) {
          this.$message.warning('主要联系人不能删除，请先设置其他联系人为主要联系人');
          return;
        }
        
        contactDelete(id).then(res => {
          if (res.success) {
            this.$message.success(res.message);
            this.loadContactList(this.model.id);
          } else {
            this.$message.warning(res.message);
          }
        });
      },
      handleContactSubmit() {
        this.contactForm.validateFields((err, values) => {
          if (!err) {
            this.contactConfirmLoading = true;
            let formData = Object.assign({}, values);
            formData.supplierId = this.model.id;
            
            let obj;
            let isPrimary = formData.isPrimary;
            
            if (!this.contactModel.id) {
              obj = contactAdd(formData);
            } else {
              formData.id = this.contactModel.id;
              // 编辑时保持原来的主要联系人状态
              formData.isPrimary = this.contactModel.isPrimary;
              obj = contactEdit(formData);
            }
            
            obj.then(res => {
              if (res.success) {
                this.$message.success(res.message);
                this.handleContactCancel();
                
                // 如果设置为主要联系人，则更新供应商信息
                if (isPrimary === '1' || isPrimary === 1) {
                  // 更新供应商的主要联系人信息
                  const updatedSupplier = {
                    id: this.model.id,
                    contactPerson: formData.name,
                    contactPhone: formData.phone,
                    email: formData.email
                  };
                  
                  // 先将其他联系人设为非主要联系人
                  const promises = this.contactList
                    .filter(contact => contact.isPrimary === 1 && contact.id !== formData.id)
                    .map(contact => {
                      const updatedContact = { ...contact, isPrimary: 0 };
                      return contactEdit(updatedContact);
                    });
                  
                  // 更新供应商信息
                  promises.push(supplierEdit(updatedSupplier));
                  
                  Promise.all(promises)
                    .then(() => {
                      this.loadData(this.model.id);
                    })
                    .catch(error => {
                      this.$message.error('更新主要联系人失败: ' + error.message);
                      this.loadContactList(this.model.id);
                    });
                } else {
                  this.loadContactList(this.model.id);
                }
              } else {
                this.$message.warning(res.message);
              }
              this.contactConfirmLoading = false;
            });
          }
        });
      },
      handleContactCancel() {
        this.contactVisible = false;
      },
      
      // 物料关联相关方法
      handleAddMaterial() {
        this.materialForm.resetFields();
        this.materialModel = {};
        this.materialTitle = "新增物料关联";
        this.materialVisible = true;
      },
      handleEditMaterial(record) {
        this.materialForm.resetFields();
        this.materialModel = Object.assign({}, record);
        this.materialTitle = "编辑物料关联";
        this.materialVisible = true;
        this.$nextTick(() => {
          this.materialForm.setFieldsValue(pick(this.materialModel, 'materialCode', 'price', 'leadTime', 'minOrderQuantity', 'isPreferred', 'materialImages', 'remark'));
        });
      },
      handleDeleteMaterial(id) {
        materialDelete(id).then(res => {
          if (res.success) {
            this.$message.success(res.message);
            this.loadMaterialList(this.model.id);
          } else {
            this.$message.warning(res.message);
          }
        });
      },
      handleMaterialSubmit() {
        this.materialForm.validateFields((err, values) => {
          if (!err) {
            this.materialConfirmLoading = true;
            let formData = Object.assign({}, values);
            formData.supplierId = this.model.id;
            
            let obj;
            if (!this.materialModel.id) {
              obj = materialAdd(formData);
            } else {
              formData.id = this.materialModel.id;
              obj = materialEdit(formData);
            }
            
            obj.then(res => {
              if (res.success) {
                this.$message.success(res.message);
                this.handleMaterialCancel();
                this.loadMaterialList(this.model.id);
              } else {
                this.$message.warning(res.message);
              }
              this.materialConfirmLoading = false;
            });
          }
        });
      },
      handleMaterialCancel() {
        this.materialVisible = false;
      },
      
      // 物料图片相关方法
      handleMaterialImagesChange(fileList) {
        console.log('物料图片变更:', fileList);
        
        // 当returnUrl为true时，fileList是字符串路径
        if (typeof fileList === 'string') {
          // 直接保存字符串路径
          this.materialImages = fileList;
          console.log('保存物料图片路径:', this.materialImages);
        } else if (Array.isArray(fileList)) {
          // 如果是数组，转换为字符串路径
          const paths = fileList.map(file => {
            if (file && typeof file === 'object' && file.response && file.response.message) {
              return file.response.message;
            } else if (file && typeof file === 'string') {
              return file;
            }
            return '';
          }).filter(Boolean).join(',');
          
          this.materialImages = paths;
          console.log('转换后的物料图片路径:', this.materialImages);
        } else {
          // 其他情况，设为空字符串
          console.warn('物料图片格式不正确:', fileList);
          this.materialImages = '';
        }
        
        // 更新表单值
        this.materialForm.setFieldsValue({
          materialImages: this.materialImages
        });
      },
      
      // 获取图片URL
      getImageUrl(text) {
        if (!text) return '';
        try {
          // 使用jeecg标准的文件访问方式
          return getFileAccessHttpUrl(text);
        } catch (error) {
          console.error('获取文件URL失败:', error);
          return '';
        }
      },
      
      // 将图片字符串转换为数组
      getImagesArray(text) {
        if (!text) return [];
        return text.split(',').filter(Boolean);
      },
      
      // 预览图片
      handlePreviewImage(text) {
        this.previewImage = this.getImageUrl(text);
        this.previewVisible = true;
      },
      
      // 处理图片加载错误
      handleImageError(e) {
        console.error('图片加载失败:', e);
        e.target.src = '';
        e.target.alt = '图片加载失败';
      }
    }
  }
</script>

<style scoped>
.ant-descriptions-item-label {
  font-weight: bold;
}

.material-images-container {
  width: 80px;
  margin: 0 auto;
}

.material-image-item {
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.material-image {
  max-width: 80px;
  max-height: 60px;
  cursor: pointer;
}
</style> 